﻿using com.nm;
using com.nm.Cache;
using com.nm.db.Models.Systems;
using com.nm.library.Helper;
using george.Helper;
using NHibernateVertica;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace VerticaAPI.comm
{
    /// <summary>
    /// 用户数据权限处理
    /// </summary>
    public static class Common
    {
        private const string USER_DATA = "user-data:";
       /// <summary>
       /// 大区key
       /// </summary>
        private const string DISTRICT_KEY = ":district-list";
        /// <summary>
        /// 省份key
        /// </summary>
        private const string AREA_KEY = ":area-list";
        /// <summary>
        /// 店铺key
        /// </summary>
        private const string SHOP_KEY = ":all-shop-list";
        /// <summary>
        /// Vertica
        /// </summary>
        private static VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        /// <summary>
        /// 获取用户大区权限
        /// </summary>
        /// <returns></returns>
        public static string GetBigAreaList(int userId)
        {
            return RedisCache.GetString(USER_DATA + userId + DISTRICT_KEY);
        }
        /// <summary>
        /// 获取用户省份权限
        /// </summary>
        /// <returns></returns>
        public static string GetPerntAreaList(int userId)
        {
            return RedisCache.GetString(USER_DATA + userId + AREA_KEY);
        }
        /// <summary>
        /// 获取用户店铺权限列表
        /// </summary>
        /// <returns></returns>
        public static string GetShopList(int userId)
        {
            var result = RedisCache.GetString(USER_DATA + userId + SHOP_KEY);
            return (string.IsNullOrWhiteSpace(result) ? "''" : result);
        }

        /// <summary>
        /// 用户数据权限保存到Redis
        /// </summary>
        /// <param name="userId"></param>
        public static void SetDataRights(int userId)
        {
            try
            {
                //if (RedisCache.Exists(USER_DATA + userId + SHOP_KEY)) return;
                var dc = new SysEntities();
                //大区
                var bigAreaList = (from a in dc.sys_userData_group
                                   join b in dc.sys_data_group on a.GroupDataID equals b.GroupDataID
                                   where a.UserID == userId
                                   select b.DistrictID).ToList().Distinct().JoinToStr(",");
                SetRedis(USER_DATA + userId + DISTRICT_KEY, bigAreaList);
                //省份
                var parentAreaList = (from a in dc.sys_userData_group
                                      join b in dc.sys_data_group on a.GroupDataID equals b.GroupDataID
                                      where a.UserID == userId
                                      select b.DataValue).ToList().Distinct().JoinToStr(",");
                SetRedis(USER_DATA + userId + AREA_KEY, parentAreaList);
                //店铺
                string sql = @"select dw.ShopID,ebap.AreaID as ParentAreaID,
                           ebap.AreaName as ParentAreaName 
                        FROM dw.dw_Shop dw
                        left join ods.ods_erp_Bas_Area eba on eba.AreaID = dw.AreaID
                        left join ods.ods_erp_Bas_Area ebap on ebap.AreaID=eba.ParentID
                        where 1=1 and ebap.AreaID in(" + (string.IsNullOrWhiteSpace(parentAreaList) ? "''" : parentAreaList) + ")";
                var dt = GetVerticaDataTable(sql);
                var groupData = ModelConvertHelper<GrupData>.ConvertToModel(dt).ToList();
                var shopGroup = groupData.Select(t => new ShopData
                {
                    ShopID = t.ShopID
                }).ToList();

                var shopQurey = dc.sys_userData_rights.Where(t => t.UserID == userId).Select(o => new ShopData
                {
                    ShopID = o.DataValue
                }).ToList();
                //合并
                var allShop = shopGroup.Concat(shopQurey).Distinct().ToList();
                var list = new List<string>();
                foreach(var shop in allShop)
                {
                    list.Add(shop.ShopID);
                }
                SetRedis(USER_DATA + userId + SHOP_KEY, list.JoinToStr(","));
            }
            catch (Exception ex)
            {
                Log.Error("数据权限合并出错：" + ex.Message);
            }
        }
        private static void SetRedis(string cacheKey,string list)
        {
            if (RedisCache.Exists(cacheKey))
                RedisCache.Remove(cacheKey);
            RedisCache.MinString(cacheKey, list, 720);
        }
        /// <summary>
        /// 执行SQL返回Table
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetVerticaDataTable(string sql)
        {
            try
            {
                var cmd = Helper.GetSqlStringCommand(sql);
                var dt = Helper.ExecuteDataTable(cmd);
                return dt;
            }catch (Exception ex)
            {
                Log.Error("执行Vertica语句出错：" + ex.Message);
                throw ex;
            }
        }


        public class ShopData
        {
            public string ShopID { get; set; }
        }
        public class GrupData: ShopData
        {
            public string ParentAreaID { get; set; }
            public string ParentAreaName { get; set; }
        }
    }
}
